package com.monkeyboy.second.threadpool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池
 *
 * @Author Gavin
 * @date 2021.04.10 11:23
 */
public class CustomThreadPool {
    public static int count = 1;

    public static void main(String[] args) throws InterruptedException {
        /**
         * ArrayBlockingQueue:有界队列,支持公平与非公平锁
         * LinkedBlockingQueue：不指定容量无界队列，但是可以传递容量
         */
        ThreadPoolExecutor myPool =
                new ThreadPoolExecutor(1, 20,
                        5000, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<>(100),
                        new ThreadPoolExecutor.AbortPolicy()//饱和策略，默认抛出异常
                );
        myPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("开始执行任务--------");
                    Thread.sleep(2000);
                    if (count % 2 == 1) {
                        int i = 1 / 0;
                    }
                    System.out.println("线程执行完毕。");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("线程任务执行失败，把当前任务重新放入队列");
                    BlockingQueue<Runnable> queue = myPool.getQueue();
                    queue.add(this);
                    count++;
                }
            }
        });
        myPool.shutdown();
    }
}
